# Contributor: Mehdi Chinoune <mehdi.chinoune@hotmail.com>

_realname=libgridxc
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=2.1.0
pkgrel=3
pkgdesc="Library for XC computation on grids. (mingw-w64)"
arch=('any')
mingw_arch=('ucrt64' 'clang64' 'clangarm64')
url='https://gitlab.com/siesta-project/libraries/libgridxc'
msys2_references=(
  'aur: libgridxc'
)
license=('spdx:BSD-3-Clause')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         $([[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]] || echo "${MINGW_PACKAGE_PREFIX}-gcc-libgfortran")
         "${MINGW_PACKAGE_PREFIX}-libxc")
makedepends=("${MINGW_PACKAGE_PREFIX}-fc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             $([[ ${CARCH} == aarch64 ]] || echo "${MINGW_PACKAGE_PREFIX}-msmpi"))
source=("https://gitlab.com/siesta-project/libraries/libgridxc/-/archive/${pkgver}/${_realname}-${pkgver}.tar.bz2"
        "001-fix-install-dll.patch"
        "002-fix-pkgconf-file.patch")
sha256sums=('58bedbeea073f30614148e5d6cbf32b572d92544990c43d525785d1654a4c5d7'
            'cc8ab14119c097257f1aaf646f187346aaf5b98b1fed7755159d2ad650abf75a'
            'cb14007fd0296258b1146e6cc5f355cde9b689d3f581fa2963d06b249fa2122a')

prepare() {
  cd "${srcdir}"/${_realname}-${pkgver}

  patch -Np1 -i "${srcdir}"/001-fix-install-dll.patch
  patch -Np1 -i "${srcdir}"/002-fix-pkgconf-file.patch
}

build() {
  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  if [[ ${CARCH} == aarch64 ]]; then
    _extra_config+=("-DLIBGRIDXC_WITH_MPI=OFF")
  else
    _extra_config+=("-DLIBGRIDXC_WITH_MPI=ON")
  fi

  local _fflags=""
  if [[ ${CARCH} == x86_64 ]]; then
    _fflags+=" -march=x86-64-v3"
  fi

  FFLAGS="${_fflags}" \
  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    "${MINGW_PREFIX}"/bin/cmake.exe \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      "${_extra_config[@]}" \
      -DBUILD_SHARED_LIBS=ON \
      -DCMAKE_DLL_NAME_WITH_SOVERSION=ON \
      -DLIBGRIDXC_WITH_LIBXC=ON \
      -DLIBGRIDXC_TESTS=OFF \
      -DFortran_FLAGS_RELEASE="-O3" \
      -S "${_realname}-${pkgver}" \
      -B "build-${MSYSTEM}"

  "${MINGW_PREFIX}"/bin/cmake.exe --build "build-${MSYSTEM}"
}

package() {
  DESTDIR="${pkgdir}" "${MINGW_PREFIX}"/bin/cmake.exe --install "build-${MSYSTEM}"

  install -Dm644 "${srcdir}"/${_realname}-${pkgver}/COPYING \
    "${pkgdir}"${MINGW_PREFIX}/share/licenses/${_realname}/COPYING
}
